package org.zhaolei.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zhaolei.enums.BizCodeEnum;
import org.zhaolei.exception.BizException;
import org.zhaolei.model.AddressDO;
import org.zhaolei.request.AddressAddRequest;
import org.zhaolei.service.AddressService;
import org.zhaolei.util.JsonData;
import org.zhaolei.vo.AddressVO;

import java.util.List;

@Api(tags = "收货地址模块")
@RestController
@RequestMapping("/api/address/v1")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @ApiOperation("新增收货地址")
    @PostMapping("add")
    public JsonData add(@ApiParam("地址对象") @RequestBody AddressAddRequest addressAddRequest) {
        addressService.add(addressAddRequest);

        return JsonData.buildSuccess();
    }

    @ApiOperation("根据id查找地址详情")
    @GetMapping("/find/{address_id}")
    public Object detail(@ApiParam(value = "地址id", required = true)
                             @PathVariable("address_id") long addressId) {
        //之前数据库连接出错，在这一步就抛异常了，所以异常码为-1
        AddressVO addressVO = addressService.detail(addressId);
//        if (addressId == 1) {
//            System.out.println("I am herer");
//            throw new BizException(-111111, "测试自定义异常");
//        }
        return addressVO == null ? JsonData.buildResult(BizCodeEnum.ADDRESS_NO_EXITS) : JsonData.buildSuccess(addressVO);
    }

    /**
     * 删除指定收货地址
     * @param addressId
     * @return
     */
    @ApiOperation("删除收货地址")
    @DeleteMapping("/del/{address_id}")
    public JsonData del(@ApiParam(value = "地址id", required = true)
                            @PathVariable("address_id") long addressId) {
        int rows = addressService.del(addressId);

        return rows == 1 ? JsonData.buildSuccess() : JsonData.buildResult(BizCodeEnum.ADDRESS_DEL_FAIL);
    }

    /**
     * 查询用户的全部收货地址
     * @return
     */
    @ApiOperation("查询用户的全部收货地址")
    @GetMapping("/list")
    public JsonData findUserAllAddress() {
        //用threadLocal获取当前登录的用户信息
        List<AddressVO> list = addressService.listUserAllAddress();

        return JsonData.buildSuccess(list);
    }
}
